#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

COV = None
if os.environ.get('FLASK_COVERAGE'):
    import coverage
    COV = coverage.coverage(branch=True, include='app/*')
    COV.start()

from flaskz import create_app, models
from extensions import db
from flask_script import (Manager, Shell, Server, prompt, prompt_pass, prompt_bool)
from flask_migrate import Migrate, MigrateCommand
from celery.bin.celery import main as celery_main

basedir = os.path.abspath(os.path.dirname(__file__))
cfg_path = os.path.join(basedir, 'config.json')
app = create_app(os.getenv('STOCK_CONFIG') or 'development', cfg_path=cfg_path)
manager = Manager(app)
migrate = Migrate(app, db)


def make_shell_context():
    return dict(app=app, db=db, models=models)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command("runserver", Server("0.0.0.0", port=9000))


@manager.command
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()


@manager.command
def celerydev():
    celery_args = ['celery', 'worker', '-B', '-s', '/tmp/celery.db', '--concurrency=100']
    with app.app_context():
        return celery_main(celery_args)


@manager.command
def create_all():
    """从model类创建数据库表结构
    """
    db.create_all()


if __name__ == '__main__':
    manager.run()
